var current_lang = '';
var current_page = 0;
var items_per_page = 10;
var firstLoad = false;

$('#search-qb').submit(function(){
	/*var s = $('input[name=s]');
	searchQB(s,0,10,10);
	
	return false; */
	//var s = $('input[name=s]').val();
	//$('input[name=s]').val(escape(s));
});

$(document).ready(function(){
	firstLoad = true;
	//if args is sent get questions
	var vars = $.getUrlVars();
	var s = vars['s'];
	var lang = vars['lang'];
	var series = vars['series'];	

	if(series && series.length != 0){
		$('#select-series').val(series).attr('selected',true);
	}

	if(lang && lang.length != 0){
		$('#select-language').val(lang).attr('selected',true);
		current_lang = lang;
	}
	
	if(s && s.length != 0){
		s = decodeURIComponent(s);
		s = s.replace(/\+/g,' ');
		$('input[name=s]').val(decodeURIComponent(s));
		
		searchQB(s,0,10,series);
	}
	/*
	if (!("autofocus" in document.createElement("input"))) {
		$('input[name=s]').focus();
	}*/
	
});

function buildPager(number_of_hits){	
	if(number_of_hits > items_per_page){
		$("#Pagination").pagination(number_of_hits, {
			items_per_page:items_per_page, 
			callback:handlePaginationClick,
			next_text: 'Next',
			prev_text: 'Prev',
			link_to:"#",
			num_edge_entries:2,
			ellipse_text: '..'
		});
	}else{
		$("#Pagination").html('');
	}
}

function handlePaginationClick(new_page_index, pagination_container) {
	
	if(new_page_index != current_page){
		var s 	= $('input[name=s]').val();
		
		var start 	= new_page_index*items_per_page;
		var end 	= (start + items_per_page);
		
		searchQB(s,start,items_per_page);
		current_page = new_page_index;
	}
	
   return false;
}

function searchQB(s,start,records,series){
	
	var data = {s:s, 
				start:start, 
				records:records};
	
	if(current_lang.length != 0){
		data.lang = current_lang;
	}
	$.ajax({
			url: backend+'qb-json.xql?callback=?',
			dataType: 'jsonp',
			data: data,
			success: searchDone
		});
}

function searchDone(data){
	var output = '';
	$.each(data.questions['d:QuestionItem'], function(i,questionItem){
		var qid = questionItem['@id'];
		var question_id =  questionItem['r:UserID']['#text']
		output += '<div id="'+qid+'" class="question-block">';
		if(questionItem['d:QuestionText'].length > 1){
			$.each(questionItem['d:QuestionText'], function(i,questionText){
				output += '<p class="'+questionText['@xml:lang']+'"><img src="img/lang/'+questionText['@xml:lang']+'.gif" />';
				output += questionText['d:LiteralText']['d:Text'];
				output += '</p>';
			});
		}else{
			output += '<p class="'+questionItem['d:QuestionText']['@xml:lang']+'"><img src="img/lang/'+questionItem['d:QuestionText']['@xml:lang']+'.gif" />';
			output += questionItem['d:QuestionText']['d:LiteralText']['d:Text'];
			output += '</p>';
		}
		output += '<div id="question-info-'+question_id+'"></div><a id="question-info-expand-'+question_id+'" href="#" class="question-info">get info</a></div>';
	});
	$("#result").html(output);
	if(data.hits > 1){
		$("#hits").html((parseInt(data.start)+1)+'-'+(parseInt(data.end))+' of '+' '+(data.hits));
	}
	//if this is the first result-set
	if(firstLoad){
		buildPager(data.hits);
		firstLoad = false;
	}

	$('.question-info').click(function(e){
		e.preventDefault();

		var qid = $(this).attr("id");
		
		qid = qid.replace('question-info-expand-','');
		$(this).addClass('question-info-loading');
		$.ajax({
			url: backend+'qb-get-study-units.xql?callback=?',
			dataType: 'jsonp',
			data: {
				qid:qid,
			},
			success: loadedQuestionInfo
		});
	});	
}

function loadedQuestionInfo(data){
	$("#question-info-expand-"+data['question-id']).removeClass('question-info-loading');
	$("#question-info-"+data['question-id']).hide(0);
	var output = '<ul class="question-in-studies-list">';
	if('study' in data){	
		if(data['study'].length > 1){
			$.each(data['study'], function(i,study){
				output += renderStudyLink(study);
			});
		}else{
			output += renderStudyLink(data.study);
		}
		output += '</ul>';
		$("#question-info-"+data['question-id']).html(output);
		$("#question-info-expand-"+data['question-id']).hide(0);
		$("#question-info-"+data['question-id']).show("fast", "linear");
	}else{
		$("#question-info-expand-"+data['question-id']).html('no studies found');
	}
	
	function renderStudyLink(study){
		var lang_arg='';
		if(current_lang.length != 0){
			lang_arg='&lang='+current_lang;
		}
		var output = '<li>'+study['questionItemName']['en']+' <a href="http://bull.ssd.gu.se:8080/exist/rest//db/ddi3/xslt/study.xql?id='+study['studyId']+lang_arg+'#question-'+data['question-id']+'">'+study['title']['en']+'</a></li>';
		return output;
	}
}




/*******************************************************************************/
// Read a page's GET URL variables and return them as an associative array.
$.extend({
	getUrlVars: function(){
		var vars = [], hash;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		for(var i = 0; i < hashes.length; i++){
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
		return vars;
	},
	getUrlVar: function(name){
		return $.getUrlVars()[name];
	}
});
